﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.SessionState;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxTreeList;
using DevExpress.XtraPrinting;
using OT.Module.Model;
using OT.Module.BLL;
using OT.BaseLibrary;
using OT.Module.Tree;
using OT.Common;
using OT.Dev;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using DevExpress.Web.Data;
using DevExpress.Xpo;
using DevExpress.Web.ASPxClasses;

public partial class Common_ComboBox : DevPage
{
    /***
     *  Page
     */

    #region Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack && !IsCallback)
        {
            // 其它控件初始化
            InitControlValue();
            // 风格设置
            InitGridStyle(InfoGrid, this.GetType().FullName);
            // 调整分页风格
            GridPagerStyleSetting(InfoGrid, PagerStyle.Pager);
        }
    }

    #endregion

    #region InitControlValue

    protected void InitControlValue()
    {

        // 下面加入页面自定义控件初始化代码
    }

    #endregion


    /***
     *  Panel & Grid
     */

    #region ajaxPanel_Callback

    protected void ajaxPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
        // 切换树节点时，要将列表之前选定的行取消
        InfoGrid.Selection.UnselectAll();
        // 数据源使用后期参数绑定，所以要调用DataBind
        InfoGrid.DataBind();
    }

    #endregion

    #region InfoGrid_PreRender

    protected void InfoGrid_PreRender(object sender, EventArgs e)
    {
        // 对列表的每一列进行自动的设置，包括
        // 1、根据字段长度自动调整列宽
        // 2、设置编辑页面的文本不换行
        AutoSettingGridColumnStyle(InfoGrid);
    }

    #endregion

    #region InfoGrid_CustomCallback

    protected void InfoGrid_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
        // 统一处理新增，批量删除，改变分页风格，打开/关闭过滤行事件
        if (HandleDefaultEvent(e.Parameters, InfoGrid, new Employee_BLL(XpoSession)))
            return;

        // 不能统一处理的事件，由页面自行处理
    }
    #endregion

    /***
     *  DataSource
     */

    #region @ dataSource_Selecting

    protected void dataSource_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
    {
        // 定制数据源获取数据时向Select函数提供的参数
        // 方便根据左边树节点的选择来过滤数据
    }

    #endregion

    #region ds_ObjectCreating

    protected void ds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
    {
        e.ObjectInstance = new Employee_BLL(XpoSession);
    }
    #endregion

    #region dsProvince_ObjectCreating

    protected void dsProvince_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
    {
        e.ObjectInstance = new Province_BLL(XpoSession);
    }
    #endregion

    #region dsCity_ObjectCreating

    protected void dsCity_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
    {
        e.ObjectInstance = new City_BLL(XpoSession);
    }
    #endregion

    #region dsCompany_ObjectCreating

    protected void dsCompany_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
    {
        e.ObjectInstance = new Company_BLL(XpoSession);
    }
    #endregion

    #region dsDepartment_ObjectCreating

    protected void dsDepartment_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
    {
        e.ObjectInstance = new Department_BLL(XpoSession);
    }
    #endregion

    /***
     *  Grid data event
     */

    #region @ InfoGrid_InitNewRow

    protected void InfoGrid_InitNewRow(object sender, DevExpress.Web.Data.ASPxDataInitNewRowEventArgs e)
    {
        // 如果树节点的信息会影响新增记录的初始属性，则在这里初始化

        // 树节点做为新增分类的默认父分类
    }

    #endregion

    #region InfoGrid_RowInserting

    protected void InfoGrid_RowInserting(object sender, ASPxDataInsertingEventArgs e)
    {
        Employee entity = new Employee(XpoSession);

        new EntityMeta<Employee>(XpoSession).SetEntityProperty(entity, e.NewValues);

        new Employee_BLL(XpoSession).Insert(entity);

        DataSourceRefreshCancel(InfoGrid, e);
    }
    #endregion

    #region InfoGrid_RowUpdating

    protected void InfoGrid_RowUpdating(object sender, ASPxDataUpdatingEventArgs e)
    {
        EntityMeta<Employee> meta = new EntityMeta<Employee>(XpoSession);

        Employee entity = XpoSession.GetObjectByKey<Employee>(e.Keys[meta.KeyProperty].ToString());
        Employee old = XpoSession.GetObjectByKey<Employee>(e.Keys[meta.KeyProperty].ToString());

        meta.SetEntityProperty(entity, e.NewValues);

        new Employee_BLL(XpoSession).Update(entity, old);

        DataSourceRefreshCancel(InfoGrid, e);
    }
    #endregion

    #region InfoGrid_RowDeleting
    protected void InfoGrid_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
        string id = e.Keys[0].ToString();

        string error = "";

        // 未通过删除校验则取消随后发送到数据逻辑层的操作
        if (!new Employee_BLL(XpoSession)._CheckDelete(id, ref error))
        {
            throw new ApplicationException(error);
        }

        new Employee_BLL(XpoSession)._DeleteByKey(id);

        DataSourceRefreshCancel(InfoGrid, e);
    }
    #endregion

    /***
     *  Validate
     */

    #region InfoGrid_RowValidating

    protected void InfoGrid_RowValidating(object sender, ASPxDataValidationEventArgs e)
    {
        Employee entity = new Employee(XpoSession);

        new EntityMeta<Employee>(XpoSession).SetEntityProperty(entity, e.NewValues);

        ValidationMDL<Employee>(entity, InfoGrid, e);
    }

    #endregion


    protected void comboDepartment_Callback(object source, CallbackEventArgsBase e)
    {
        if (string.IsNullOrEmpty(e.Parameter))
            return;

        dsDepartment.SelectParameters[0].DefaultValue = e.Parameter;
        comboDepartment.DataBind();
    }

    protected void InfoGrid_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
    {
        if (!InfoGrid.IsEditing ) return;
        if (e.KeyValue == DBNull.Value || e.KeyValue == null) return;

        if (e.Column.FieldName == "CityID")
        {
            object val = InfoGrid.GetRowValuesByKeyValue(e.KeyValue, "ProvinceID");
            if (val == DBNull.Value) return;
            string provId = (string)val;

            // 保证初始化城市列表时按当前省份过滤
            // 使用联动方案，不用考虑客户端关联
            dsCity.SelectParameters[0].DefaultValue = provId;
        }
        else if (e.Column.FieldName == "DepartmentID")
        {
            object val = InfoGrid.GetRowValuesByKeyValue(e.KeyValue, "CompanyID");
            if (val == DBNull.Value) return;
            string companyId = (string)val;

            // 保证初始化部门列表时按当前公司过滤
            dsDepartment.SelectParameters[0].DefaultValue = companyId;

            ASPxComboBox combo = e.Editor as ASPxComboBox;
            FillDepartmentCombo(combo, companyId);

            combo.Callback += new CallbackEventHandlerBase(cmbDepartment_OnCallback);
        }
    }

    private void cmbDepartment_OnCallback(object source, CallbackEventArgsBase e)
    {
        FillDepartmentCombo(source as ASPxComboBox, e.Parameter);
    }

    protected void FillDepartmentCombo(ASPxComboBox cmb, string companyId)
    {
        XPCollection<Department> depts = new Department_BLL(XpoSession).Select(companyId);
        cmb.Items.Clear();
        foreach (Department dept in depts)
            cmb.Items.Add(dept.Name, dept.ID);
    }

}
